<template>
  <!-- 吸边按钮 -->
  <div class="floating-button" @click.stop="toggleCalculator" :class="{ expanded: isExpanded, 'slide-out': isSlideOut }">
    <div class="floating-button-close" @click.stop="slideOut" v-show="!isSlideOut && !isExpanded">
      <RightOutlined />
    </div>
    <div class="floating-button-open" @click.stop="slideIn" v-show="isSlideOut && !isExpanded">
      <LeftOutlined />
    </div>
    <div class="button-content">
      <template v-if="!isExpanded">
        <div class="mini-header">
          <div class="mini-date">{{ formattedDateShort }}</div>
          <div class="mini-time">{{ currentTimeStr }}</div>
        </div>

        <div class="mini-section">
          <div class="section-label">工作进度</div>
          <div class="mini-progress">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${progressPercentage}%` }"></div>
            </div>
            <div class="progress-text">{{ progressPercentage }}%</div>
          </div>
        </div>

        <div class="mini-section" v-if="showResult">
          <div class="section-label">今日已赚</div>
          <div class="mini-amount">¥{{ earnedTodayFormatted }}</div>
        </div>
      </template>
      <template v-else>
        <div class="close-icon">×</div>
      </template>
    </div>
  </div>

  <!-- 展开的计算器 -->
  <div class="salary-calculator" v-show="isExpanded">
    <h1>工资计算器</h1>

    <div v-if="!showResult || isEditing">
      <a-form layout="vertical">
        <a-form-item label="月工资 (元)">
          <a-input-number v-model:value="monthlySalary" :min="0" :step="100" style="width: 100%" placeholder="请输入月工资" />
        </a-form-item>

        <a-form-item label="上班时间">
          <a-input v-model:value="startWorkTimeStr" placeholder="请输入上班时间 (格式: HH:mm)" />
        </a-form-item>

        <a-form-item label="下班时间">
          <a-input v-model:value="endWorkTimeStr" placeholder="请输入下班时间 (格式: HH:mm)" />
        </a-form-item>

        <a-form-item label="休息制度">
          <a-radio-group v-model:value="weekendType" button-style="solid">
            <a-radio-button value="double">双休</a-radio-button>
            <a-radio-button value="single">单休</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="startCalculate" :disabled="!isFormValid">开始计算</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div v-if="showResult && !isEditing" class="result-container">
      <a-card :bordered="false" :title="cardTitle">
        <template #extra>
          <a-tag :color="isHoliday ? 'red' : isWeekend ? 'orange' : 'green'">
            {{ dayTypeText }}
          </a-tag>
        </template>

        <div class="salary-info">
          <div class="today-date">{{ formattedDate }}</div>
          <div class="current-time">{{ currentTimeStr }}</div>

          <div class="progress-container">
            <div class="progress-label">
              <span>工作进度</span>
              <span>{{ progressPercentage }}%</span>
            </div>
            <a-progress :percent="progressPercentage" :stroke-color="progressColor" :status="workStatus" />
          </div>

          <div class="salary-amount">
            <div class="amount-label">今日已赚</div>
            <div class="amount-value">¥ {{ earnedTodayFormatted }}</div>
          </div>

          <div class="salary-details">
            <div class="detail-item">
              <span>日工资基数</span>
              <span>¥ {{ dailySalaryBaseFormatted }}</span>
            </div>
            <div class="detail-item">
              <span>工作时长</span>
              <span>{{ workHoursPerDay.toFixed(1) }}小时</span>
            </div>
            <div class="detail-item">
              <span>时薪</span>
              <span>¥ {{ hourlyRateFormatted }}</span>
            </div>
            <div class="detail-item">
              <span>今日系数</span>
              <span>{{ dayRateMultiplier }}x</span>
            </div>
            <div class="detail-item">
              <span>本月工作日</span>
              <span>{{ workdaysInMonth }}天</span>
            </div>
          </div>

          <div class="action-buttons">
            <a-button type="primary" @click="editSettings">重新设置</a-button>
          </div>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useVacationStore } from '@/stores/vacation'
import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 状态
const monthlySalary = ref(10000)
const startWorkTimeStr = ref('09:00')
const endWorkTimeStr = ref('18:00')
const currentTime = ref(dayjs())
const timer = ref(null)
const weekendType = ref('double') // 默认双休
const showResult = ref(false)
const isEditing = ref(false)
const isExpanded = ref(false) // 控制计算器是否展开
const isSlideOut = ref(false)

// 切换计算器展开/收起状态
function toggleCalculator() {
  isExpanded.value = !isExpanded.value
}

// 计算每天工作小时
const workHoursPerDay = computed(() => {
  if (!startWorkTimeStr.value || !endWorkTimeStr.value) return 8 // 默认值

  const startMinutes = getMinutesFromTimeStr(startWorkTimeStr.value)
  const endMinutes = getMinutesFromTimeStr(endWorkTimeStr.value)

  if (startMinutes === null || endMinutes === null) return 8 // 默认值

  // 计算工作时长（小时）
  return (endMinutes - startMinutes) / 60
})

// 从时间字符串获取分钟数
function getMinutesFromTimeStr(timeStr) {
  if (!isValidTimeFormat(timeStr)) return null

  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours * 60 + minutes
}

// 表单验证
const isFormValid = computed(() => {
  return monthlySalary.value > 0 && startWorkTimeStr.value && endWorkTimeStr.value && isValidTimeFormat(startWorkTimeStr.value) && isValidTimeFormat(endWorkTimeStr.value) && workHoursPerDay.value > 0
})

// 验证时间格式
function isValidTimeFormat(timeStr) {
  const regex = /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/
  return regex.test(timeStr)
}

// 本地存储键名
const STORAGE_KEY = 'salary-calculator-settings'

// 保存设置到本地存储
function saveSettings() {
  const settings = {
    monthlySalary: monthlySalary.value,
    startWorkTimeStr: startWorkTimeStr.value,
    endWorkTimeStr: endWorkTimeStr.value,
    weekendType: weekendType.value,
    isSlideOut: isSlideOut.value
  }
  localStorage.setItem(STORAGE_KEY, JSON.stringify(settings))
}

// 从本地存储加载设置
function loadSettings() {
  const settingsJson = localStorage.getItem(STORAGE_KEY)
  if (settingsJson) {
    try {
      const settings = JSON.parse(settingsJson)
      monthlySalary.value = settings.monthlySalary || 10000
      startWorkTimeStr.value = settings.startWorkTimeStr || '09:00'
      endWorkTimeStr.value = settings.endWorkTimeStr || '18:00'
      weekendType.value = settings.weekendType || 'double'
      isSlideOut.value = settings.isSlideOut || false
      return true
    } catch (e) {
      console.error('加载设置失败:', e)
    }
  }
  return false
}

// 开始计算
function startCalculate() {
  if (isFormValid.value) {
    saveSettings()
    showResult.value = true
    isEditing.value = false
  }
}

// 重新设置
function editSettings() {
  isEditing.value = true
  showResult.value = false // 隐藏收入信息
}

// 获取节假日数据
const vacationStore = useVacationStore()
const currentYear = new Date().getFullYear()

// 修改组件挂载时的逻辑
onMounted(async () => {
  if (Object.keys(vacationStore.holidayData).length === 0) {
    await vacationStore.fetchHolidayData(currentYear)
  }

  // 从本地存储加载设置
  const hasSettings = loadSettings()

  // 如果有保存的设置，设置showResult为true
  if (hasSettings) {
    showResult.value = true
  }

  // 设置定时器，每秒更新当前时间
  timer.value = setInterval(() => {
    currentTime.value = dayjs()
  }, 1000)
})

onUnmounted(() => {
  // 清除定时器
  if (timer.value) {
    clearInterval(timer.value)
  }
})

// 监听设置变化，自动保存
watch(
  [monthlySalary, startWorkTimeStr, endWorkTimeStr, weekendType],
  () => {
    if (showResult.value && !isEditing.value) {
      saveSettings()
    }
  },
  { deep: true }
)

// 监听滑出状态变化，自动保存
watch(isSlideOut, () => {
  saveSettings()
})

// 计算属性
const formattedDate = computed(() => {
  return currentTime.value.format('YYYY年MM月DD日')
})

const formattedDateShort = computed(() => {
  return currentTime.value.format('MM-DD')
})

const currentTimeStr = computed(() => {
  return currentTime.value.format('HH:mm:ss')
})

// 判断今天是否是节假日或周末
const today = computed(() => {
  return currentTime.value.format('YYYY-MM-DD')
})

const isHoliday = computed(() => {
  return vacationStore.holidayData[today.value]?.holiday === true
})

const isWeekend = computed(() => {
  const dayOfWeek = currentTime.value.day()
  return weekendType.value === 'double'
    ? dayOfWeek === 0 || dayOfWeek === 6 // 双休：周六和周日都是周末
    : dayOfWeek === 0 // 单休：只有周日是周末
})

const dayTypeText = computed(() => {
  if (isHoliday.value) return '节假日'
  if (isWeekend.value) return '周末'
  return '工作日'
})

// 计算本月工作日数量
const workdaysInMonth = computed(() => {
  const currentMonth = currentTime.value.month() + 1
  const currentYear = currentTime.value.year()
  const daysInMonth = currentTime.value.daysInMonth()

  let workdays = 0

  for (let day = 1; day <= daysInMonth; day++) {
    const date = dayjs(`${currentYear}-${currentMonth}-${day}`).format('YYYY-MM-DD')
    const dayOfWeek = dayjs(date).day()

    // 获取当天的节假日信息
    const holidayInfo = vacationStore.holidayData[date]

    // 判断是否是法定节假日或调休工作日
    const isHolidayDay = holidayInfo?.holiday === true // 法定节假日
    const isWorkdayDay = holidayInfo?.holiday === false // 调休工作日

    // 如果是法定节假日，不计入工作日
    if (isHolidayDay) {
      continue
    }

    // 如果是调休工作日，计入工作日
    if (isWorkdayDay) {
      workdays++
      continue
    }

    // 判断是否是周末
    const isWeekendDay =
      weekendType.value === 'double'
        ? dayOfWeek === 0 || dayOfWeek === 6 // 双休：周六和周日都是周末
        : dayOfWeek === 0 // 单休：只有周日是周末

    // 如果是周末，不计入工作日
    if (isWeekendDay) {
      continue
    }

    // 其他情况为正常工作日
    workdays++
  }

  return workdays
})

// 计算日工资基数（月工资除以当月工作日数）
const daysInMonth = computed(() => {
  return currentTime.value.daysInMonth()
})

const dailySalaryBase = computed(() => {
  // 使用工作日数量而不是月天数
  return monthlySalary.value / workdaysInMonth.value
})

const dailySalaryBaseFormatted = computed(() => {
  return dailySalaryBase.value.toFixed(2)
})

// 计算时薪
const hourlyRate = computed(() => {
  return dailySalaryBase.value / workHoursPerDay.value
})

const hourlyRateFormatted = computed(() => {
  return hourlyRate.value.toFixed(2)
})

// 计算今日系数（节假日3倍，周末2倍，工作日1倍）
const dayRateMultiplier = computed(() => {
  if (isHoliday.value) return 3
  if (isWeekend.value) return 2
  return 1
})

// 计算工作进度
const startWorkTimeMinutes = computed(() => {
  if (!startWorkTimeStr.value) return 0
  const [hours, minutes] = startWorkTimeStr.value.split(':').map(Number)
  return (isNaN(hours) ? 0 : hours) * 60 + (isNaN(minutes) ? 0 : minutes)
})

const endWorkTimeMinutes = computed(() => {
  if (!endWorkTimeStr.value) return 0
  const [hours, minutes] = endWorkTimeStr.value.split(':').map(Number)
  return (isNaN(hours) ? 0 : hours) * 60 + (isNaN(minutes) ? 0 : minutes)
})

const currentTimeMinutes = computed(() => {
  return currentTime.value.hour() * 60 + currentTime.value.minute() + currentTime.value.second() / 60
})

const totalWorkMinutes = computed(() => {
  if (!startWorkTimeMinutes.value || !endWorkTimeMinutes.value) return 0
  return endWorkTimeMinutes.value - startWorkTimeMinutes.value
})

const elapsedWorkMinutes = computed(() => {
  if (currentTimeMinutes.value < startWorkTimeMinutes.value) {
    return 0
  } else if (currentTimeMinutes.value > endWorkTimeMinutes.value) {
    return totalWorkMinutes.value
  } else {
    return currentTimeMinutes.value - startWorkTimeMinutes.value
  }
})

const progressPercentage = computed(() => {
  if (totalWorkMinutes.value <= 0) return 0
  const percentage = (elapsedWorkMinutes.value / totalWorkMinutes.value) * 100
  return Math.min(100, Math.max(0, parseFloat(percentage.toFixed(2))))
})

const workStatus = computed(() => {
  if (elapsedWorkMinutes.value <= 0) {
    return 'normal'
  } else if (elapsedWorkMinutes.value >= totalWorkMinutes.value) {
    return 'success'
  } else {
    return 'active'
  }
})

const progressColor = computed(() => {
  if (isHoliday.value) {
    return { from: '#ff4d4f', to: '#ff7875' }
  } else if (isWeekend.value) {
    return { from: '#fa8c16', to: '#ffc53d' }
  } else {
    return { from: '#108ee9', to: '#87d068' }
  }
})

// 计算今日已赚金额
const earnedToday = computed(() => {
  const hourlyRateWithMultiplier = hourlyRate.value * dayRateMultiplier.value
  return (elapsedWorkMinutes.value / 60) * hourlyRateWithMultiplier
})

const earnedTodayFormatted = computed(() => {
  return earnedToday.value.toFixed(2)
})

// 卡片标题
const cardTitle = computed(() => {
  return '今日收入'
})

// 向右滑出
function slideOut(e) {
  e.stopPropagation()
  isSlideOut.value = true
}

// 滑回来
function slideIn(e) {
  e.stopPropagation()
  isSlideOut.value = false
}
</script>

<style scoped>
.salary-calculator-container {
  position: relative;
}

.floating-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 120px;
  border-radius: 12px;
  background: linear-gradient(135deg, #344767, #344767);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  transition: all 0.3s ease;
  padding: 12px;
  transform: translateX(0);
}

.floating-button.slide-out {
  transform: translateX(calc(100% + 20px));
}

.floating-button-close,
.floating-button-open {
  position: absolute;
  transform: rotateY(-50%);
  left: -20px;
  width: 20px;
  height: 80px;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background: linear-gradient(135deg, #344767, #344767);
  border-radius: 10px 0 0 10px;
  transition: all 0.3s ease;
}

.floating-button-open {
  z-index: -1;
  opacity: 0;
  pointer-events: none;
}

.floating-button.slide-out .floating-button-open {
  z-index: 1001;
  opacity: 1;
  pointer-events: auto;
  /* left: -30px; */
}

.floating-button:hover {
  transform: translateY(-2px);
}

.floating-button.slide-out:hover {
  transform: translateX(calc(100% + 20px));
}

.floating-button.expanded {
  background: linear-gradient(135deg, #ff4d4f, #cf1322);
  width: 60px;
  height: 60px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.mini-header {
  width: 100%;
  text-align: center;
  margin-bottom: 6px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 4px;
}

.mini-date {
  font-size: 12px;
  opacity: 0.9;
}

.mini-time {
  font-size: 18px;
  font-weight: bold;
  margin-top: 2px;
}

.mini-section {
  width: 100%;
  margin-bottom: 6px;
}

.section-label {
  font-size: 11px;
  opacity: 0.8;
  margin-bottom: 3px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.mini-progress {
  width: 100%;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 2px;
}

.progress-fill {
  height: 100%;
  background-color: white;
  border-radius: 3px;
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  text-align: right;
  font-weight: bold;
}

.mini-amount {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.close-icon {
  font-size: 24px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.salary-calculator {
  position: fixed;
  right: 20px;
  bottom: 180px;
  width: 350px;
  max-height: 80vh;
  overflow-y: auto;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  padding: 20px;
  z-index: 999;
}

.result-container {
  margin-top: 24px;
}

.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.salary-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.today-date {
  font-size: 16px;
  color: #666;
}

.current-time {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.progress-container {
  margin: 8px 0;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.salary-amount {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 16px 0;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.amount-label {
  font-size: 16px;
  color: #666;
}

.amount-value {
  font-size: 32px;
  font-weight: bold;
  color: #344767;
}

.salary-details {
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-item span:first-child {
  color: #666;
}

.detail-item span:last-child {
  font-weight: bold;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 添加动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.salary-calculator {
  animation: fadeIn 0.3s ease-out;
}

/* 添加悬浮按钮的脉动效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 104, 104, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(24, 144, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(24, 144, 255, 0);
  }
}

.floating-button:not(.expanded) {
  animation: pulse 2s infinite;
}
</style>
